import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../API/admin/admin.dart';

class AdminController extends GetxController {
  final RxList<dynamic> items = <dynamic>[].obs;
  final RxInt currentPage = 1.obs;
  final RxInt totalItems = 0.obs;
  final RxBool isLoading = false.obs;
  final RxInt totalPages = 1.obs;

  @override
  void onInit() {
    super.onInit();
    loadPage(currentPage.value);
  }

  Future<void> loadPage(int page) async {
    try {
      isLoading.value = true;
      final response = await AdminApiService.searchGoods(page);

      if (response['code'] == 20041) {
        final data = response['data'];
        items.assignAll(data['list'] as List);
        totalItems.value = data['total'];
        currentPage.value = page;
        totalPages.value = (data['total'] / 30).ceil();
      } else {
        Get.snackbar('错误', '加载失败: ${response['message']}');
      }
    } catch (e) {
      Get.snackbar('异常', '加载数据异常: $e');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> handleReview(int itemId, bool approve) async {
    final confirmed = await Get.dialog(
      AlertDialog(
        title: Text(approve ? '通过审核' : '拒绝审核'),
        content: Text('确定要${approve ? '通过' : '拒绝'}该商品的审核吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      final response = approve
          ? await AdminApiService.approveItem(itemId: itemId)
          : await AdminApiService.rejectItem(itemId:itemId);

      if (response['code'] == 20031) {
        // 审核成功后重新加载当前页
        await loadPage(currentPage.value);
      } else {
        Get.snackbar('错误', '操作失败: ${response['message']}');
      }
    } catch (e) {
      Get.snackbar('异常', '操作异常: $e');
    }
  }

  void previousPage() {
    if (currentPage.value > 1) {
      loadPage(currentPage.value - 1);
    }
  }

  void nextPage() {
    if (currentPage.value < totalPages.value) {
      loadPage(currentPage.value + 1);
    }
  }
}